package com.cat.admin.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cat.admin.service.SysDeptService;
import com.cat.common.entity.SysDept;
import com.cat.common.entity.UserInfo;
import com.cat.common.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author dd-cat
 * @version 1.0
 * @date 2020-10-12 17:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/dept")
@Api(value = "dept", tags = "部门模块")
public class SysDeptController {
    private final SysDeptService deptService;

    /**
     * 部门树
     *
     * @return 部门信息
     */
    @GetMapping("tree")
    public List<Tree<Long>> tree() {
        Set<SysDept> all = new HashSet<>(deptService.list());
        return deptService.treeDept(all);
    }

    @GetMapping("list")
    public List<SysDept> list(SysDept dept) {
        return deptService.list(Wrappers.query(dept));
    }

    /**
     * 通过ID查询
     *
     * @param id ID
     */
    @GetMapping("/{id}")
    public SysDept getById(@PathVariable Integer id) {
        return deptService.getById(id);
    }

    /**
     * 添加
     *
     * @param sysDept 实体
     */
    @PostMapping
    public boolean save(@Valid @RequestBody SysDept sysDept) {
        return deptService.save(sysDept);
    }

    /**
     * 删除
     *
     * @param ids ids
     */
    @DeleteMapping("/{ids}")
    public boolean removeByIds(@PathVariable List<Long> ids) {
        return deptService.removeByIds(ids);
    }

    /**
     * 编辑
     *
     * @param sysDept 实体
     */
    @PutMapping
    public boolean update(@Valid @RequestBody SysDept sysDept) {
        UserInfo user = SecurityUtils.getUser();
        sysDept.setUpdateTime(LocalDateTime.now());
        sysDept.setUpdateBy(user.getUsername());
        return deptService.updateById(sysDept);
    }
}
